package com.example.demovote.mapper;

import com.example.demovote.entity.Items;
import com.example.demovote.entity.Vote;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * <p>
 * 投票系统-题目表-2 Mapper 接口
 * </p>
 *
 * @author ly
 * @since 2024-03-18
 */
public interface VoteMapper extends BaseMapper<Vote> {

    @Select("<script>" +
            "select a.*,b.icnt,c.ucnt from tp_vote a \n" +
            "left join ( select vid, count(*) icnt from tp_items group by vid ) b on a.id=b.vid\n" +
            "left join ( select vid, count(usid) ucnt from tp_record group by vid) c on a.id = c.vid" +
            "<where>" +
            "<if test='vname != null'>a.vname like concat('%',#{vname},'%')</if>" +
            "</where>" +
            "</script>")
    public List<Vote> selectWithCnt(@Param("vname") String vname);

    @Select("select a.*,b.icnt,c.ucnt from tp_vote a \n" +
            "left join ( select vid, count(*) icnt from tp_items group by vid ) b on a.id=b.vid\n" +
            "left join ( select vid, count(usid) ucnt from tp_record group by vid) c on a.id = c.vid" +
            " where id=#{id}")
    // 查询选项需要使用关联查询
    @Results(
            value={
                    @Result( column = "id", property = "id"),
                    @Result( column = "id", property = "items", many = @Many(
                            select = "selectItemsByVid"
                    ))
            }
    )
    public Vote selectById(int id);

    @Select("select a.*,b.cnt from tp_items a" +
            " left join (select vid, iid, count(*) cnt from tp_record where vid=#{vid} GROUP BY iid,vid) b on a.id=b.iid" +
            " where a.vid=#{vid}")
    public List<Items> selectItemsByVid(int vid);


}
